package com.spring.demo.publicutil.util;

import java.io.File;
import java.io.IOException;

/**
 * 删除下载失败的依赖
 */
public class DeleteLoserDependent {
    public static void main(String[] args) {
        String mavenRepoPath = "D:\\sort\\Java\\maven\\repository";
        System.out.println("Scanning Maven repository at: " + mavenRepoPath);
        cleanFailedDownloads(mavenRepoPath);
    }

    public static void cleanFailedDownloads(String repositoryPath) {
        File repoDir = new File(repositoryPath);
        if (!repoDir.exists() || !repoDir.isDirectory()) {
            System.err.println("Invalid repository path: " + repositoryPath);
            return;
        }

        int deletedFiles = 0;
        try {
            // 递归遍历仓库目录
            deletedFiles = scanAndDeleteFailedDependencies(repoDir);
        } catch (IOException e) {
            System.err.println("Error while cleaning repository: " + e.getMessage());
        }

        System.out.println("Cleaning completed. Deleted " + deletedFiles + " corrupted/incomplete files.");
    }

    private static int scanAndDeleteFailedDependencies(File dir) throws IOException {
        int count = 0;
        File[] files = dir.listFiles();
        if (files == null) return 0;

        for (File file : files) {
            if (file.isDirectory()) {
                count += scanAndDeleteFailedDependencies(file);
            } else {
                // 检查常见的下载失败文件特征
                if (isFailedDownload(file)) {
                    System.out.println("Deleting: " + file.getAbsolutePath());
                    if (file.delete()) {
                        count++;
                    } else {
                        System.err.println("Failed to delete: " + file.getAbsolutePath());
                    }
                }
            }
        }

        // 删除空目录
        if (dir.listFiles().length == 0) {
            dir.delete();
        }

        return count;
    }

    private static boolean isFailedDownload(File file) {
        String name = file.getName();

        // 检查常见的下载失败文件
        if (name.endsWith(".lastUpdated") ||
                name.endsWith(".tmp") ||
                name.endsWith(".incomplete") ||
                name.contains("download")) {
            return true;
        }

        // 检查文件大小是否异常小（可能是未完成下载）
        if (file.length() < 100 && (name.endsWith(".jar") || name.endsWith(".pom"))) {
            return true;
        }

        return false;
    }
}
